<template>
    <div class="fund-query">
        <vxe-table
            :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
            :footer-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
            :data="tableData"
            :key="tableKey + 'tableKey'"
            v-loading="loading"
            border
            stripe
            resizable
            :auto-resize="true"
            :sort-config="{
                defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                remote: true,
            }"
            highlight-current-row
            @sort-change="changeTableSort"
            :resizable-config="{ minWidth: '60' }"
            ref="table"
            show-header-overflow="tooltip"
            show-footer-overflow="tooltip"
            header-align="center"
        >
            <vxe-column
                v-for="item in showFieldList"
                :field="item.id"
                :title="item.content"
                :key="item.content"
                :align="getAlign(item)"
                :min-width="item.minWidth || '105px'"
                show-overflow="tooltip"
                sortable
            >
                <template slot-scope="scope">
                    <span v-if="formatParam.includes(item.id)">{{ numberFormat(scope.row[item.id], 2) || '--' }} </span>
                    <span v-else-if="['confirmDate'].includes(item.id)">
                        {{ dateFormat(scope.row[item.id]) || '--' }} {{ timeFormat(scope.row['time']) }}
                    </span>
                    <span v-else-if="['dealDate'].includes(item.id)">
                        {{ dateFormat(scope.row[item.id]) || '--' }} {{ timeFormat(scope.row['directTime']) }}
                    </span>
                    <!-- <span v-else-if="['time'].includes(item.id)">
                        {{ timeFormat(scope.row[item.id]) || '--' }}
                    </span> -->
                    <span v-else>
                        {{ scope.row[item.id] === 0 || (scope.row[item.id] && (scope.row[item.id] + '').trim()) ? scope.row[item.id] : '--' }}
                    </span>
                </template>
            </vxe-column>
        </vxe-table>
        <risk-pagination :paging="page" @page-change="pageRet"></risk-pagination>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            :reset-no-selected-field-list="resetNoSelectedFieldList"
            table-name="TN_OUTER_CONFIRM"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import { dateFormat, numberFormat, timeFormat } from '@/utils/tools';
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({ name: 'OuterConfirm', components: { RiskTableLayout, RiskPagination } })
export default class OuterConfirm extends Vue {
    @Prop()
    transData: any;

    numberFormat = numberFormat;
    dateFormat = dateFormat;
    timeFormat = timeFormat;

    layoutDialog: boolean = false; // 布局显示值

    showFieldList: any[] = []; // 展示字段

    selectedFieldList: any[] = []; // 已选字段

    fixedFieldList: any[] = [
        { id: 'realdealSerialNo', content: '成交序号(恒生)', minWidth: '130px' },
        { id: 'dealNo', content: '成交编号(恒生)', minWidth: '130px' },
    ];

    tableData: any[] = []; // 表格数据

    tableKey: number = -1;

    loading: boolean = false; // 页面渲染

    private sortProp: string = 'realdealSerialNo'; // 排序字段

    private sortOrder: string = 'asc'; // 排序方式

    sort: string = 'L_REALDEAL_SERIAL_NO ASC'; // 默认排序字段

    private page: pages = {
        currentPage: 1,
        pageSize: 10,
        total: 0,
    };

    resetNoSelectedFieldList = [
        { id: 'fundId', content: '产品序号' },
        { id: 'fundName', content: '产品名称' },
    ];

    // 表格字段
    tableColumns = [
        { id: 'realdealSerialNo', content: '成交序号(恒生)', minWidth: '150px', align: 'left' },
        { id: 'dealNo', content: '成交编号(恒生)', minWidth: '150px', align: 'left' },
        { id: 'dailyInstructionNo', content: '指令序号(恒生)', minWidth: '150px', align: 'left' },
        { id: 'indexDailyModify', content: '指令修改序号(恒生)', minWidth: '160px', align: 'left' },
        { id: 'batchSerialNo', content: '指令批号(恒生)', minWidth: '140px', align: 'left' },
        { id: 'confirmNo', content: '确认编号', align: 'left' },
        { id: 'confirmDate', content: '确认日期', align: 'center' },
        // { id: 'time', content: '确认时间', align: 'center' },
        { id: 'dealDate', content: '成交日期', align: 'center', minWidth: '180px' },
        // { id: 'directTime', content: '成交时间', align: 'center' },
        { id: 'fundId', content: '产品序号', align: 'left' },
        { id: 'fundName', content: '产品名称', align: 'left' },
        { id: 'basecombiId', content: '组合编码', align: 'left' },
        { id: 'combiName', content: '组合名称', align: 'left' },
        { id: 'interCode', content: '证券代码', align: 'left' },
        { id: 'stockNameSt', content: '证券名称', align: 'left' },
        { id: 'stockType', content: '证券类别', align: 'center' },
        { id: 'assetClass', content: '资产分类', align: 'center' },
        { id: 'investType', content: '投资类型', align: 'center' },
        { id: 'businClass', content: '业务分类', align: 'center' },
        { id: 'businProType', content: '业务过程分类', minWidth: '130px', align: 'center' },
        { id: 'entrustDirection', content: '委托方向', align: 'center' },
        { id: 'marketName', content: '交易市场', align: 'center' },
        { id: 'balance', content: '金额' },
        { id: 'amount', content: '数量' },
        { id: 'price', content: '价格' },
        { id: 'bonusType', content: '分红方式', align: 'center' },
        { id: 'seatId', content: '席位' },
        { id: 'currencyNo', content: '币种', align: 'left' },
        { id: 'status', content: '状态', align: 'center' },
        { id: 'operatorNo', content: '操作员编码', minWidth: '140px', align: 'left' },
        { id: 'operatorName', content: '操作员名称', minWidth: '140px', align: 'left' },
        { id: 'rivalId', content: '交易对手编码', minWidth: '150px', align: 'left' },
        { id: 'name', content: '交易对手名称', minWidth: '150px', align: 'left' },
    ];

    // 需格式化字段
    formatParam = ['balance', 'price', 'amount'];

    // 排序字段
    sortableObj = {
        fundId: 'L_FUND_ID',
        fundName: 'VC_FUND_NAME',
        amount: 'EN_AMOUNT',
        assetClass: 'C_ASSET_CLASS',
        balance: 'EN_BALANCE',
        basecombiId: 'L_BASECOMBI_ID',
        batchSerialNo: 'L_BATCH_SERIAL_NO',
        bonusType: 'C_BONUS_TYPE',
        businClass: 'C_BUSIN_CLASS',
        businProType: 'C_BUSIN_PRO_TYPE',
        combiName: 'VC_COMBI_NAME',
        confirmDate: 'CONCAT(L_CONFIRM_DATE,L_TIME)',
        confirmNo: 'L_CONFIRM_NO',
        currencyNo: 'VC_CURRENCY_NO',
        dailyInstructionNo: 'L_DAILY_INSTRUCTION_NO',
        dealDate: 'CONCAT(L_DEAL_DATE,L_DIRECT_TIME)',
        dealNo: 'VC_DEAL_NO',
        directTime: 'L_DIRECT_TIME',
        entrustDirection: 'C_ENTRUST_DIRECTION',
        indexDailyModify: 'L_INDEX_DAILY_MODIFY',
        interCode: 'VC_INTER_CODE',
        investType: 'C_INVEST_TYPE',
        marketName: 'VC_MARKET_NAME',
        name: 'VC_NAME',
        operatorName: 'VC_OPERATOR_NAME',
        operatorNo: 'L_OPERATOR_NO',
        price: 'EN_PRICE',
        realdealSerialNo: 'L_REALDEAL_SERIAL_NO',
        rivalId: 'L_RIVAL_ID',
        seatId: 'VC_SEAT_ID',
        status: 'C_STATUS',
        stockNameSt: 'VC_STOCK_NAME',
        stockType: 'C_STOCK_TYPE',
        time: 'L_TIME',
    };
    isFirst: boolean = true;
    currentRecord: any = {};
    @Watch('transData', { immediate: true, deep: true })
    async handleTab(nowVal, oldVal) {
        if (nowVal['activeTab'] == 'outer-confirm') {
            this.layoutDialog = nowVal.detailLayoutDialog;
            if (this.isFirst) {
                await this.queryLayout();
                this.getOuterConfirmTableData();
                this.isFirst = false;
            } else if (
                !oldVal ||
                JSON.stringify(oldVal.clickRow) !== JSON.stringify(nowVal.clickRow) ||
                JSON.stringify(nowVal.clickRow) !== JSON.stringify(this.currentRecord)
            ) {
                this.currentRecord = JSON.parse(JSON.stringify(nowVal.clickRow));
                !oldVal && (await this.queryLayout());
                this.getOuterConfirmTableData();
            }
        }
    }

    @Watch('layoutDialog')
    handleLayoutDialog() {
        this.$emit('layout-handle', this.layoutDialog);
    }

    getOuterConfirmTableData() {
        this.loading = true;
        this.$axios
            .post('/productSelect/outerConfirm', {
                paging: this.page,
                sort: this.sort,
                productCode: this.transData.clickRow.fundCode,
                productSerialNo: this.transData.clickRow.fundId,
            })
            .then((res: any) => {
                this.tableData = res.list;
                this.page.total = res.total;
                this.loading = false;
            })
            .catch(() => {
                this.loading = false;
            });
    }

    pageRet() {
        this.getOuterConfirmTableData();
    }

    // 分页
    pageChange(curPage: number) {
        this.page.currentPage = curPage;
        this.getOuterConfirmTableData();
    }

    // 排序改变
    private changeTableSort(column): void {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        let sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        this.sort = this.sortableObj[column.property] + ' ' + sortType;
        this.pageChange(1);
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/TN_OUTER_CONFIRM')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (!resList) {
            // 新用户初始化
            const keys = this.resetNoSelectedFieldList.map(item => item.id);
            this.showFieldList = this.tableColumns.filter(item => !keys.includes(item.id));
            const fixKeys = this.fixedFieldList.map(item => item.id);
            this.selectedFieldList = this.showFieldList.filter(item => !fixKeys.includes(item.id));
        } else {
            this.selectedFieldList = JSON.parse(resList);
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
        }
        this.tableKey++;
    }

    getAlign(ele) {
        let obj = this.tableColumns.find(item => item.id == ele.id);
        return (obj && obj.align) || 'right';
    }
}
</script>
<style lang="scss" scoped></style>
